package com.common.secretkey.rsa2;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AsymmetricEncryptionExample {
    public static void main(String[] args) {
        try {
            // 生成 RSA 密钥对
            KeyPair keyPair = generateKeyPair();

            // 待加密的原始数据
            String originalData = "Hello, world!";

            // 使用公钥加密数据
            String encryptedData = encryptData(originalData, keyPair.getPublic());

            // 使用私钥解密数据
            String decryptedData = decryptData(encryptedData, keyPair.getPrivate());

            System.out.println("原始数据：" + originalData);
            System.out.println("加密后的数据：" + encryptedData);
            System.out.println("解密后的数据：" + decryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 生成 RSA 密钥对
    private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);  // 指定密钥长度为 2048 bits
        return keyPairGenerator.generateKeyPair();
    }

    // 使用公钥加密数据
    private static String encryptData(String data, java.security.PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 使用私钥解密数据
    private static String decryptData(String encryptedData, java.security.PrivateKey privateKey) throws Exception {
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}
